﻿using AutoDeployForSims.Entity;
using AutoDeployForSims.Model;
using AutoDeployForSims.ViewModel;
using MyUtility.Utility;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AutoDeployForSims.Service
{
    public class StatusCheckService
    {
       
        private GetConfigService getConfigService = SingletonProvider<GetConfigService>.Instance;
        private Thread CheckThread;

        public bool IsRunning { get; set; }

        public StatusCheckService()
        {
            
        }

        public bool StartCheckThread()
        {
            bool isRight = false;

            CheckThread = new Thread(new ThreadStart(CheckAppThread))
            {
                IsBackground = true
            };
            CheckThread.Start();

            return isRight;
        }

        public bool StopCheckThread()
        {
            bool isRight = false;
            if (CheckThread != null)
            {
                CheckThread.Abort();
            }

            return isRight;
        }


        private void CheckAppThread()
        {
            AppInfoModel appInfoModel = SingletonProvider<AppInfoModel>.Instance;
            List<AppStatusEntity> appStatusEntities;
            
            //开启循环
            while (true)
            {
                appStatusEntities = appInfoModel.AppStatusEntities;
                lock (appStatusEntities)
                {
                    foreach (var item in appStatusEntities)
                    {
                        bool ststusTemp = false;
                        //从任务管理器里查找
                        Process[] process = Process.GetProcesses();
                        foreach (var processItem in process)
                        {
                            if (processItem.ProcessName == item.AppName)
                            {
                                ststusTemp = true;
                            }
                            item.IsRunning = ststusTemp;
                        }
                    }
                }
                
                //2秒查询一次
                Thread.Sleep(2000);
            }
        }

    }
}
